import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:color_dart/rgba_color.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertz/components/a_button/index.dart';
import 'package:fluttertz/components/a_dialog/a_dialog.dart';
import 'package:fluttertz/components/a_row/a_row.dart';
import 'package:fluttertz/utils/global.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wifi_configuration/wifi_configuration.dart';

class Ljwifi extends StatefulWidget {
  Ljwifi({Key key}) : super(key: key);

  _LjwifiState createState() => _LjwifiState();
}

class _LjwifiState extends State<Ljwifi> {
  SharedPreferences prefs;
  String _wifiname = "";
  String _wifipwd = "";
  String _jtname = "";
  String _jt_serial = "AI-THINKER_XXXX";
  String _jt_serial0 = "";
  String _kind = "";

  TextEditingController _controller_wifiname;
  TextEditingController _controller_wifipwd;
  TextEditingController _controller_jtname;

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero, () async {
      connectSocket();

      prefs = await SharedPreferences.getInstance();
      _wifiname = prefs.getString('wifiname');
      _wifipwd = prefs.getString('wifipwd');

      String wifiname = G.user.selectWifi;
      String wifipwd = "";
      if (_wifiname != null &&
          _wifipwd != null &&
          _wifiname.compareTo(wifiname) == 0) {
        wifipwd = _wifipwd;
      }

      _controller_wifiname = new TextEditingController(text: wifiname);
      _controller_wifipwd = new TextEditingController(text: wifipwd);
      _controller_jtname = new TextEditingController(text: "");
      setState(() {});
    });

    _timer = Timer.periodic(Duration(seconds: 1), (timer) async {
      checkjtonline(context);
    });

    getWifiList(); //获取wifi列表
  }

  var _listAvailableWifi;
  int _wifiListLen = 0;

  //仅android可用， 并且手机需开启位置
  void getWifiList() async {
    _listAvailableWifi = await WifiConfiguration.getWifiList();
    _wifiListLen = _listAvailableWifi.length;
  }

  Timer _timer;

  Socket mSocket = null;

  //socket连接状态   -1 未连接 0 已连接，等待回传信息 1 已连接，已回传装置编号，可以发送wifi+psw 2 发送wifi+psw信息确认  3-checkjtonline确认已上线
  int _connectstate = -1; //socket连接状态

  connectSocket() async {
    // String host = "192.168.1.229"; //test
    // int port = 8901;
    String host = "192.168.4.1";
    int port = 8080;
    G.loading.show(context);
    try {
      await Socket.connect(host, port, timeout: Duration(seconds: 5))
          .then((socket) {
        //连接成功
        _connectstate = 0;
        mSocket = socket;

        mSocket.listen((var data) {
          String rawData = utf8.decode(data);
          // if (rawData.contains(">AI-THINKER_") || awData.contains(">AI-THINKER_"))
          if (rawData.contains(">AI-THINKER") || rawData.contains(">DF-COMPANY") || rawData.contains(">AI-COMPANY") || rawData.contains(">DF-THINKER")) {
            //连接成功可以发msg
            _connectstate = 1;
            List<String> keyArr = rawData.split(',');
            //>AI-THINKER_A881A5,FE99,0000*
            if (keyArr.length > 0) {
              _jt_serial = keyArr[0];
              if (rawData.contains(">DF-COMPANY")) {
                _kind = "DF";
                _jt_serial0 = "DF-COMPANY";
                _jt_serial = _jt_serial.replaceAll(">DF-COMPANY_", "");
              } else if (rawData.contains(">AI-COMPANY")) {
                _kind = "AI";
                _jt_serial0 = "AI-COMPANY";
                _jt_serial = _jt_serial.replaceAll(">AI-COMPANY_", "");
              } else if (rawData.contains(">DF-THINKER")) {
                _kind = "DF";
                _jt_serial0 = "DF-THINKER";
                _jt_serial = _jt_serial.replaceAll(">DF-THINKER_", "");
              } else {
                //AI-THINKER
                _kind = "AI";
                _jt_serial0 = "AI-THINKER";
                _jt_serial = _jt_serial.replaceAll(">AI-THINKER_", "");
              }

              G.toastlong('連接裝置Wi-Fi成功，請設置！');
              G.loading.hide(context);
              setState(() {});
            }
          }

          if (rawData.contains("AT+CWJAP=")) {
            _connectstate = 2;
            // G.loading.hide(context);
            // G.toast('設置成功！');
            // G.loading.show(context);
            G.toast('連接成功, 请等待1分钟連線確認！');
            setState(() {});
          }
        });
      });
    } catch (e) {
      // G.toast("未連接socket出現異常，e=${e.toString()}");
      G.loading.hide(context);
      G.toast("未連接裝置Wi-Fi！");
      Navigator.pop(context);
    }
  }

  bool _issend = false; //设置只发送一次

  sendSocket() async {
    _wifiname = _controller_wifiname.text;
    _wifipwd = _controller_wifipwd.text;
    prefs.setString('wifiname', _wifiname);
    prefs.setString('wifipwd', _wifipwd);
    if (_issend) {
      return;
    }
    _issend = true;
    G.loading.show(context);
    String msg = "AT+CWJAP=\"$_wifiname\",\"$_wifipwd\"";
    mSocket?.write(msg);
  }

  bool _issaveok = false; //机台保存成功

  doSave(BuildContext context) async {
    _jtname = _controller_jtname.text;
    if (_jtname.isEmpty) {
      return G.toast('請輸入機台名！');
    }

    G.loading.show(context);
    int adminid = G.user.data.adminid;
    try {
      Response response;
      Dio dio = Dio();

      response = await dio.post("https://aps.acciot.com.tw/api/taizhu/addjt",
          queryParameters: {
            "adminid": adminid,
            "jt_serial": _jt_serial,
            "jt_serial0": _jt_serial0,
            "kind": _kind,
            "jtname": _jtname
          });

      if (response == null) {
        return G.toast('請連接回行動網路或可連網之WIFI再選擇保存！');
      }

      Map<String, dynamic> resCallbackMap = response.data;

      G.loading.hide(context);

      int code = resCallbackMap['code'];
      if (code == 1) {
        // G.toast('機台保存成功, 请等待1分钟連線確認！');
        G.toast('機台保存成功！');
        // Navigator.of(context).popUntil(ModalRoute.withName("/home"));
        // G.loading.show(context);
        // _issaveok = true;
        Navigator.of(context).popUntil(ModalRoute.withName("/home"));
      } else if (code == -1) {
        G.toast('錯誤的用戶ID!');
      } else if (code == -2) {
        G.toast('已更新機台名稱保存!');
        Navigator.of(context).popUntil(ModalRoute.withName("/home"));
      }
      return null;
    } catch (e) {
      G.loading.hide(context);
    }
  }

  bool _ischeckjtonlineing = false;

  int _num = 0; //等待30秒后再检查

  checkjtonline(BuildContext context) async {
    if (_connectstate != 2 || _ischeckjtonlineing) {
      return;
    }
    _num++;
    if (_num < 10) {
      return;
    }
    //_connectstate == 2 才检测是否上线
    _ischeckjtonlineing = true;
    try {
      Response response;
      Dio dio = Dio();

      response = await dio.post(
          "https://aps.acciot.com.tw/api/taizhu/checkjtonline",
          queryParameters: {"jt_serial": _jt_serial});

      _ischeckjtonlineing = false;
      if (response == null) {
        return G.toast('請連接回行動網路或可連網之WIFI！');
      }

      Map<String, dynamic> resCallbackMap = response.data;

      int code = resCallbackMap['code'];
      if (code != 1 && _num > 50) {
        G.loading.hide(context);
        G.toastlong('機台超時沒有上線，請再重新啟動裝置， 以及確認 wifi 密碼，重新設置!');
        Future.delayed(Duration(milliseconds: 3000), () {
          Navigator.of(context).popUntil(ModalRoute.withName("/home"));
        });

      } else if (code == 1) {
        G.loading.hide(context);
        _num = -1000;
        G.toastlong('機台已上線!');
        _connectstate = 3;
        setState(() {

        });
      }
      return null;
    } catch (e) {
      G.loading.hide(context);
      _ischeckjtonlineing = false;
    }
  }

  @override
  void dispose() {
    mSocket?.close();
    _timer?.cancel();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
            image: DecorationImage(
          image: AssetImage("lib/assets/images/tz/bg.png"),
          fit: BoxFit.cover,
        )),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            centerTitle: true,
            title: Text(
              "步驟 2",
              style: TextStyle(
                  color: rgba(0, 0, 0, 1),
                  fontSize: 18,
                  fontWeight: FontWeight.bold),
            ),
            backgroundColor: Colors.transparent,
            elevation: 0,
            automaticallyImplyLeading: false,
            leading: context == null
                ? null
                : InkWell(
                    child: icontupian8(color: rgba(44, 44, 44, 1), size: 16),
                    onTap: () {
                      if (!_issaveok) {
                        ADialog.confirm(context, content: "您尚未保存機台，請確認是否返回首頁?",
                            confirmButtonPress: () {
                          Future.delayed(Duration.zero, () {
                            Navigator.of(context)
                                .popUntil(ModalRoute.withName("/home"));
                          });
                        });
                      }
                    },
                  ),
            bottom: PreferredSize(
              child: Container(
                decoration: BoxDecoration(
                    border:
                        G.borderBottom(color: Colors.transparent, show: false)),
              ),
              preferredSize: Size.fromHeight(0),
            ),
          ),
          body: Container(
            color: Colors.transparent,
            padding: EdgeInsets.only(left: 35, right: 35, top: 30),
            child: Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(bottom: 20),
                  color: Colors.transparent,
                  width: 100,
                  height: 94,
                  child: Image.asset(
                    'lib/assets/images/tz/bg_wifi01.png',
                    fit: BoxFit.cover,
                  ),
                ),
                ARow(
                    height: 80,
                    color: Colors.transparent,
                    leftChild: Text(
                      '名稱',
                      style:
                          TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                    ),
                    centerChild: Container(
                      height: 50,
                      margin: EdgeInsets.only(left: 10),
                      decoration: new BoxDecoration(
                          border: new Border.all(
                              color: Color(0x66000000), width: 0.5),
                          color: Color(0xFFFFFF),
                          borderRadius: new BorderRadius.circular((5.0))),
                      child: TextField(
                        keyboardType: TextInputType.text,
                        controller: _controller_wifiname,
                        decoration: InputDecoration(
                            counterText: "",
                            contentPadding: EdgeInsets.only(left: 10),
                            border: InputBorder.none,
                            hintText: "請輸入Wi-Fi名稱",
                            hintStyle: TextStyle(
                              fontSize: 14,
                            )),
                        onChanged: (e) {
                          _wifiname = e;
                        },
                      ),
                    ),
                    rightChild: Platform.isIOS
                        ? null
                        : Container(
                            height: 50,
                            margin: EdgeInsets.only(left: 8),
                            child: AButton.normal(
                                child: Text('搜尋',
                                    style: TextStyle(
                                        fontSize: 18,
                                        fontWeight: FontWeight.bold)),
                                type: 'info',
                                onPressed: () {
                                  showModalBottomSheet(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return Container(
                                          padding: EdgeInsets.only(
                                              left: 0, right: 0, bottom: 20),
                                          child: ListView.builder(
                                            itemBuilder: (BuildContext context,
                                                int index) {
                                              return wifirow(index);
                                            },
                                            // itemExtent: 100.0, //确定每一个item的高度 会让item加载更加高效
                                            itemCount: _wifiListLen,
                                          ),
                                        );
                                      });
                                }),
                          )),
                ARow(
                  height: 80,
                  color: Colors.transparent,
                  leftChild: Text(
                    '密碼',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  centerChild: Container(
                    height: 50,
                    margin: EdgeInsets.only(left: 10),
                    decoration: new BoxDecoration(
                        border: new Border.all(
                            color: Color(0x66000000), width: 0.5),
                        color: Color(0xFFFFFF),
                        borderRadius: new BorderRadius.circular((5.0))),
                    child: TextField(
                      keyboardType: TextInputType.text,
                      controller: _controller_wifipwd,
                      decoration: InputDecoration(
                          counterText: "",
                          contentPadding: EdgeInsets.only(left: 10),
                          border: InputBorder.none,
                          hintText: "請輸入WiFi密碼",
                          hintStyle: TextStyle(
                            fontSize: 14,
                          )),
                      onChanged: (e) {
                        _wifipwd = e;
                      },
                    ),
                  ),
                ),
                ARow(
                  height: 80,
                  color: Colors.transparent,
                  leftChild: Text(
                    '機台名稱',
                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  centerChild: Container(
                    height: 50,
                    margin: EdgeInsets.only(left: 10),
                    decoration: new BoxDecoration(
                        border: new Border.all(
                            color: Color(0x66000000), width: 0.5),
                        color: Color(0xFFFFFF),
                        borderRadius: new BorderRadius.circular((5.0))),
                    child: TextField(
                      keyboardType: TextInputType.text,
                      controller: _controller_jtname,
                      decoration: InputDecoration(
                          counterText: "",
                          contentPadding: EdgeInsets.only(left: 10),
                          border: InputBorder.none,
                          hintText: "請輸入4位數以上機台名稱",
                          hintStyle: TextStyle(
                            fontSize: 14,
                          )),
                      onChanged: (e) {
                        setState(() {
                          _jtname = e;
                        });
                      },
                    ),
                  ),
                ),
                sendbtn(),
                savebtn(),
                Container(
                    margin: EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                    // color: rgba(136, 175, 213, 1),
                    width: double.infinity,
                    child: Text(
                      "機台编号: $_jt_serial",
                      style: TextStyle(fontSize: 16),
                    )),
              ],
            ),
          ),
        ));
  }

  Widget sendbtn() {
    if (_connectstate >= 1) {
      return Container(
          margin: EdgeInsets.symmetric(vertical: 15, horizontal: 10),
          width: double.infinity,
          child: AButton.normal(
            child: Text('設置裝置',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            type: 'info',
            onPressed: () {
              sendSocket();
            },
          ));
    } else {
      return Container(
          margin: EdgeInsets.symmetric(vertical: 15, horizontal: 10),
          width: double.infinity,
          child: AButton.normal(
            child: Text('設置裝置',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            type: 'info',
          ));
    }
  }

  Widget savebtn() {
    if (_connectstate == 3 && _jtname.isNotEmpty) {
      return Container(
          margin: EdgeInsets.symmetric(horizontal: 10),
          width: double.infinity,
          child: AButton.normal(
              child: Text('保存',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
              type: 'info',
              onPressed: () {
                doSave(context);
              }));
    } else {
      return Container(
          margin: EdgeInsets.symmetric(horizontal: 10),
          width: double.infinity,
          child: AButton.normal(
            child: Text('保存',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            type: 'info',
          ));
    }
  }

  Widget wifirow(int index) {
    return ARow(
      onPressed: () {
        _controller_wifiname.text = _listAvailableWifi[index];
        setState(() {});
        Navigator.of(context).pop();
      },
      height: 50,
      centerChild: Container(
        margin: EdgeInsets.only(left: 10),
        child: Text(
          '${_listAvailableWifi[index]}',
          style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
        ),
      ),
    );
  }
}
